import {LoginModel} from '../../models/loginModel.js'
import { Storage} from '../../models/storage.js'
import { StoreModel } from '../../models/storeModel.js'
let loginModel = new LoginModel()
let storage = new Storage()
let storeModel = new StoreModel()
let app = getApp()
Page({
  data: {
    type: 0,
    mobileNumber: 0,
    score: 0,
    ticket: 0,
    cardNumber: 0,
    userId:0,
    storeList:[],
    currentStore:{},
    imgUrls:[],
    isDefined: true,//默认图，逻辑待完善
    defaultStore:{},
    allButtomListTxt: ['绑定会员卡', '会员权益', '积分兑换', '购物小票', '适用门店', '优惠券', '400-888-9448', '授权登录', ''],
    allButtomListImage: ['card_bindhyk.png', 'card_quanyi.png', 'card_duihuan.png', 'card_xiaopiao.png', 'card_mengdian.png', 'card_hjquang.png', 'card_dianhua.png', 'card_logingo1.png', '']
  },
  onLoad: function (options) {
    if (options) {
      this.setData({
        defaultStore: options
      })
    } 
    if (app.accessTokenDic == '') {
      console.log(`未登录`)
      loginModel.getLogincode()
        .then(res => {
          return loginModel.getOpenid(res)
        }).then(res => {
          storage.setStorage('openid', res, 'openid')
          let key = res.session_key
          let openid = res.openid
          let unionid = res.unionid
          let reqData = { 'openId': openid, 'unionId': unionid, 'type': 'weixin' }
          return loginModel.getServerKey(reqData)
        }).then(res => {
          storage.setStorage('fwServerKey', res, 'fwServerKey')
          app.accessTokenDic = res
          return loginModel.getUserinfo()
        }).then(res => {
          storage.setStorage('haiwaigouUserKey', res.object, 'haiwaigouUserKey')
          app.userInfodic = res.object
          return loginModel.getCardInfo()
        }).then(res => {
          if (res.returnCode == '-60000012' || res.returnCode == '-60000014' || res.returnCode == '-7') {
            let refreshToken = app.accessTokenDic.refreshToken;
            let accessToken = app.accessTokenDic.accessToken;
            let reqData = { 'grantType': 'refresh_token', 'refreshToken': refreshToken, 'accessToken': accessToken };
            loginModel.refreshToken(reqData)
              .then(res => {
                app.accessTokenDic = res;
                storage.setStorage('fwServerKey', res, 'fwServerKey')
              })
          } else {
            storage.setStorage('UserCardinfo', res, 'UserCardinfo')
            this.setData({
              type: res.type,
              mobileNumber: res.mobileNumber,
              score: res.score,
              ticket: res.ticket,
              cardNumber: res.cardNumber,
              userId: res.userId
            })
            this._setpageButton(res.type)
            this._getStoreList()
          }
        })
    }else{
      console.log(`已登录`)
      storage.getStorage('UserCardinfo')
      .then(res=>{
        this.setData({
          type: res.type,
          mobileNumber: res.mobileNumber,
          score: res.score,
          ticket: res.ticket,
          cardNumber: res.cardNumber,
          userId: res.userId
        })
        this._setpageButton(res.type)
        this._getStoreList()
      })
    }
    
  },
  onReady: function () {
    
  },
  onShow: function () { 
  },
  OnswitchStore(e) {
    wx.navigateTo({
      url: `../shopStore/shopStore?storeName=${e.currentTarget.dataset.name}`,
    })
  },
  _setpageButton(type) {
    if (type == null) {
      this.setData({
        allButtomListTxt: ['绑定会员卡', '会员权益', '积分兑换', '购物小票', '积分商城', '适用门店', '优惠券', '400-888-9448', '授权登录'],
        allButtomListImage: ['card_bindhyk.png', 'card_quanyi.png', 'card_duihuan.png', 'card_xiaopiao.png', 'card_jfsc.png', 'card_mengdian.png', 'card_hjquang.png', 'card_dianhua.png', 'card_logingo1.png']
      })
    } else {
      if (type == '901') {
        this.setData({
          allButtomListTxt: ['绑定会员卡', '会员权益', '积分兑换', '购物小票', '积分商城', '适用门店', '优惠券', '400-888-9448', ''],
          allButtomListImage: ['card_bindhyk.png', 'card_quanyi.png', 'card_duihuan.png', 'card_xiaopiao.png', 'card_jfsc.png', 'card_mengdian.png', 'card_hjquang.png', 'card_dianhua.png', '']
        })
      } else {
        this.setData({
          allButtomListTxt: ['会员权益', '积分兑换', '购物小票', '积分商城', '适用门店', '优惠券', '400-888-9448', '', ''],
          allButtomListImage: ['card_quanyi.png', 'card_duihuan.png', 'card_xiaopiao.png', 'card_jfsc.png', 'card_mengdian.png', 'card_hjquang.png', 'card_dianhua.png', '', '']
        })
      }
    }
  },
  _getStoreList(){
    let reqData = { 'pageSize': '20' }
    storeModel.getStoreList(reqData)
    .then(res => {
      this.setData({
        storeList: res.object.result
      })
      if (res.object.result) {
        return storeModel.getLocation()
      }
    }).then(res => {//用户授权位置成功
      let latitude = res.latitude
      let longitude = res.longitude
      let storeList = this.data.storeList
      let index = 0
      let indexDistance
      for (let i = 0; i < storeList.length; i++) {
        let distancelat = latitude - storeList[i].lat
        let distancelng = longitude - storeList[i].lng
        let distance = Math.abs(distancelat * distancelat) + Math.abs(distancelng * distancelng)
        if (i == 0) {
          indexDistance = distance
        }
        if (indexDistance > distance) {
          index = i
          indexDistance = distance
        }
      }
      this.setData({
        currentStore: storeList[index]
      });
      storeModel._addFirstImageUrl({
        storeList: storeList,
        currentStore: this.data.currentStore
      }).then(res => {
        this.setData({
          imgUrls: res,
          isDefined: false,
        });
      })
    }, err => {//用户授权位置失败,使用默认门店
      console.log(err +`用户授权位置失败,使用默认门店`)
    })
  },
  OniconClick(e) {
    let name = e.detail.name
    console.log(name)
    let jumpUrl = '';
    if (name == '400-888-9448') {
      wx.makePhoneCall({
        phoneNumber: '4008889448'
      })
    } else if (name == '绑定会员卡') {//绑定会员卡 
      jumpUrl = '../bandCard/bandCard'
    } else if (name == '会员权益') {//会员权益
      jumpUrl = ''
    } else if (name == '积分兑换') {//积分兑换
      jumpUrl = '../couponExchange/couponExchange'
    } else if (name == '优惠券') {//优惠卷
      jumpUrl = '../couponList/couponList'
    } else if (name == '适用门店') {//适用门店
      jumpUrl = 'orderStoreList/orderStoreList'
    } else if (name == '购物小票') {//购物小票
      jumpUrl = 'shoppingList/shoppingList?cNumber=' + this.data.cartInfoData['cardNumber'];
    } else if (name == '授权登录') {
      this.jumpLogin();
    } else if (name == '线上余额充值') {
      // jumpUrl = '../personal/balanceIndex/balanceIndex'
    } else if (name == '双旦有礼') {
      jumpUrl = '/pages/answer/sdIndex';
    } else if (name == '积分商城') {
      wx.navigateToMiniProgram({
        appId: 'wx245f0d3ed4dbca10',
        path: 'pages/index/mall/mall',
        extarData: {
          open: 'happy'
        },
        envVersion: 'release',
        success: res => {
          console.log(res)
        }
      });
      jumpUrl = '';
    }
    //跳转
    if (jumpUrl.length > 0) {
      wx.navigateTo({
        url: jumpUrl
      })
    }
  }
})